# Define here the models for your spider middleware
"""
中间键
process_request 对请求对象进行处理
process_exception 异常处理
"""
import json
import random

# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from fake_useragent import UserAgent
from scrapy import signals

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
from scrapy.http import HtmlResponse
from selenium import webdriver


class Day14SpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)


class Day14DownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)


class RandomUAMiddleware:
    def __init__(self):
        self.ua = UserAgent()

    def process_request(self, request, spider):
        request.headers['User-Agent'] = self.ua.random
        print(request.headers['User-Agent'])
        return None

    def process_response(self, request, response, spider):
        print('PUA response')
        return response


class IPProxyMiddleware:
    def __init__(self):
        with open(r'./kuaidaili_ip.json', 'r', encoding='utf-8') as f:
            self.proxies = json.load(f)

    def random_ip(self, request, spider):
        if spider.name == 'test':
            ips = list(self.proxies.keys())
            if ips:
                ip = random.choice(ips)
                print(ip)
                request.meta['proxy'] = 'http://' + ip

    def process_request(self, request, spider):
        self.random_ip(request, spider)
        return None #返回None的意思是执行完这个中间键后要接着去往下一个中间键

    def process_exception(self, request, exception, spider):
        print('process_exception')
        self.random_ip(request, spider)

    def process_response(self, request, response, spider):
        print('IP response')
        return response


class SeleniumMiddleware:
    """
    定义SeleniumMiddleware中间键
    对请求进行拦截
    用Selenium得到页面源码信息
    对页面源码信息做处理
    绕过一些反爬  js加载性质的反爬
    """

    def __init__(self):
        self.options = webdriver.ChromeOptions()  # 创建谷歌浏览器的options对象来接收浏览器的相关设置

        self.options.add_argument('--start-maximized')  # 最大化窗口
        self.options.add_argument('--incognito')  # 无痕浏览
        self.options.add_argument('--disable-extensions')  # 禁用浏览器的扩展程序,避免干扰网站的打开
        self.options.add_experimental_option("detach", True)  # 禁止浏览器自动关闭
        self.options.add_experimental_option('excludeSwitches', ['enable-automation'])
        self.options.add_experimental_option('useAutomationExtension', False)

        #去掉无头操作
        # options.add_argument('--headless')
        # options.add_argument(
        #     'user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"', )
        # options.add_argument('--disable-gpu')

    def process_request(self, request, spider):
        """
        对请求对象进行处理
        如果爬虫对象是pixabay_videos
        并且请求中的meta中需要开启SeleniumMiddleware中间键
        就需要进行Selenium处理
        如果没有就返回False
        :param request:请求对象
        :param spider:爬虫对象
        :return:
        """
        if spider.name == 'pixabay_videos':
            if request.meta.get('SeleniumMiddleware', False):   #如果meta中的值为SeleniumMiddleware则进入if 没有则返回False
                print('process_request')
                driver = webdriver.Chrome(self.options)  # 创建谷歌浏览器驱动对象
                driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
                    'source': '''
                    Object.defineProperty(navigator, 'webdriver',{get:() => false})
                    '''
                })  #反反爬
                driver.get(request.url)     #驱动对象打开请求网址 从而绕过js加载    让页面加载完直接得到页面的源代码返回
                # 让页面加载完直接得到页面的源代码返回
                return HtmlResponse(
                    url=driver.current_url, #响应地址
                    body=driver.page_source,    #响应体
                    encoding='utf-8',
                    request=request,    #请求对象
                )
        return None
